// 傀儡端操作

// 将之前桌面流代码拷贝回来，创建桌面流
async function getScreenStream() {
  // 捕获桌面流的过程
  const sources = await ipcRenderer.invoke('desktopCapturer-getSources')
  return new Promise((resolve, reject) => {
    navigator.webkitGetUserMedia(
      {
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: sources[0].id,
            widht: window.screen.width,
            height: window.screen.height,
          },
        },
      },
      (stream) => {
        // peer.emit('add-stream', stream)
        resolve(stream)
      },
      (err) => {
        console.log(err)
      },
    )
  })
}

// 创建一个RTCPeerConnection实例
const pc = new window.RTCPeerConnection({})

/** STUN打洞 */
pc.onicecandidate = (e) => {
  if (e.candidate) {
    // 这个事件在 RTCPeerConnection 创建成功自动发起
    // 发送 candidate 到傀儡端
    console.log('🚀 ~ peer-pupet.js:38 ~ candidate:', JSON.stringify(e.candidate))
    ipcRenderer.send('forward', 'pupet-candidate', e.candidate)
  }
}
// 接收后面傀儡端发送过来的 IceEvent(一样的事情傀儡度端再做一遍)
let candidates = []
// 调用时需要拿到第一个 candidate
async function addIceCandidate(candidate) {
  // pc.remoteDescription 没设置完成，先将candidate 放缓冲池存起来
  // 有可能是 null
  if (candidate) {
    candidates.push(candidate)
  }
  // 等待 pc.remoteDescription 设置完成后再添加 IceCandidate
  if (pc.remoteDescription && pc.remoteDescription.type) {
    for (let i = 0; i < candidates.length; i++) {
      await pc.addIceCandidate(new RTCIceCandidate(candidates[i]))
    }
    candidates = []
  }
}
ipcRenderer.on('candidate', (e, candidate) => {
  addIceCandidate(candidate)
})
// window.addIceCandidateRemote = addIceCandidate
/** STUN打洞 ======= end ====== */

// 创建 createAnswer Offer
async function createAnswer(offer) {
  // 获取桌面流
  const stream = await getScreenStream()
  // pc.addStrema(stream)
  stream.getTracks().forEach((track) => {
    pc.addTrack(track, stream)
  })

  // 设置 remote offer
  await pc.setRemoteDescription(offer)
  await pc.setLocalDescription(await pc.createAnswer(offer)) // 创建 answer
  console.log('answer', JSON.stringify(pc.localDescription)) // 打印 answer
  return pc.localDescription
}

// 收到控制端通过 forward 发送到 ws 的 offer 被返回
ipcRenderer.on('offer', async (offer) => {
  // 收到 offer 事件，创建 answer
  const answer = await createAnswer(offer)

  // 发送 answer
  ipcRenderer.send('forward', 'answer', { type: answer.type, sdp: answer.sdp })
  // ipcRenderer.send('forward', 'answer', { answer: answer })
})
// window.createAnswer = createAnswer
